package group.rober.common.service;

import group.rober.common.autoconfigure.CommonProperties;
import group.rober.common.entity.FileEntity;
import group.rober.runtime.kit.FileKit;
import group.rober.runtime.kit.IOKit;
import group.rober.runtime.kit.MapKit;
import group.rober.runtime.kit.ValidateKit;
import group.rober.sql.core.DataQuery;
import group.rober.sql.core.DataUpdater;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileManageService {
    @Autowired
    private CommonProperties commonProperties;
    @Autowired
    private DataQuery dataQuery;
    @Autowired
    private DataUpdater dataUpdater;

    private String directory="/";

    public String getDirectory() {
        return directory;
    }

    public void setDirectory(String directory) {
        this.directory = directory;
    }


    protected String getFileRealPath(final String relativePath){
        String startPath = commonProperties.getFileStorageRoot()+directory;
        String endPath = relativePath;
        if(!startPath.endsWith("/"))startPath = startPath+"/";
        if(endPath.startsWith("/"))endPath = endPath.substring(1);
        return startPath + endPath;
    };

    public FileEntity saveFile(FileEntity fileEntity, InputStream inputStream) throws IOException {
        ValidateKit.notNull(fileEntity);
        ValidateKit.notBlank(fileEntity.getStoredContent(),"必需要指定文件存储位置");
        dataUpdater.save(fileEntity);

        String realPath = getFileRealPath(fileEntity.getStoredContent());
        File saveFile = new File(realPath);

        OutputStream outputStream = FileKit.openOutputStream(saveFile,true);
        IOKit.copy(inputStream,outputStream,commonProperties.getFileBufferSize());
        return fileEntity;
    }

    public FileEntity getFileEntity(String fileId){
        return dataQuery.selectOne(FileEntity.class,"select * from COMO_FILE where ID=:id", MapKit.mapOf("id",fileId));
    }
    public void delete(String fileId){
        FileEntity fileEntity = getFileEntity(fileId);
        if(fileEntity == null)return;

        //找到文件并删除
        String realPath = getFileRealPath(fileEntity.getStoredContent());
        File file = new File(realPath);
        file.delete();
        //删除文件记录
        dataUpdater.delete(fileEntity);
    }

    public InputStream openInputStream(String fileId) throws IOException {
        FileEntity fileEntity = getFileEntity(fileId);
        if(fileEntity == null)return null;

        //找到文件并删除
        String realPath = getFileRealPath(fileEntity.getStoredContent());
        return FileKit.openInputStream(new File(realPath));
    }

}
